<?php
namespace app\shouyin\admin;
use app\system\admin\Admin;
use app\shouyin\model\Course as CourseModel;
use app\finance\model\Account as AccountModel;
use app\user\model\User as UserModel;
use app\system\model\systemUser as systemUserModel;
use app\shouyin\model\UserCard as UserCardModel;
use app\shouyin\model\UserBalanceLog as UserBalanceLogModel;
use app\product\model\Project as ProjectModel;
use app\product\model\Product as ProductModel;
use app\shouyin\model\UserCardLog as UserCardLogModel;

use think\Db;
class Aftermarket extends Admin
{
	public function initialize()
    {
		parent::initialize();
        $admin = systemUserModel::get(ADMIN_ID);

        $this->assign('admin_type',$admin['type']);

        // $this->assign('admin_type',$admin['type']);
        if ($this->request->action() != 'index' && !$this->request->isPost()) {
            $where['shop_id'] = session('shop_id');
            // 会员
            $userArr = UserModel::all();
            $users = UserModel::getSelect($userArr);
            $this->assign('users', $users);
            $this->assign('userArr', $userArr);

            $account_arr = AccountModel::where('status',1)->where('id','<>',0)->all();
            
            $accounts = AccountModel::getSelect($account_arr);

            
            $this->assign('accounts', $accounts);
            // 顾问
            $admins = systemUserModel::where($where)->all();
            $advisers = [];
            $technician = [];
            $cashiers = [];
            foreach ($admins as $key => $value) {
                if($value['type'] == '顾问'){
                    $advisers[] = $value;
                }else if($value['type'] == '美容师'){
                    $technician[] = $value;
                }else if($value['type'] == '前台'){
                	$cashiers[] = $value;
                }
            }
            // halt();
            $this->assign('cashiers', $cashiers);
            $this->assign('adviserArr', $advisers);
            $this->assign('advisers', systemUserModel::getSelect($advisers));
            $this->assign('technicians', systemUserModel::where('type', 7)->where('shop_id',session('shop_id'))->field('id as value,nick as name')->all());

        }
    }
	/**
	 * [refund 退款]
	 * @return [type] [description]
	 */
	public function refund()
	{
		if($this->request->isAjax()){
			$page = $this->request->param('page');
			$limit = $this->request->param('limit');
			// $page = $this->request->param('page');
			$data['data'] = Db::name('aftermarket_liao')->where('shop_id',session('shop_id'))->order('id desc')->select();
			foreach ($data['data'] as $key => $value) {
				$data['data'][$key]['user_name'] = Db::name('user')->where('id',$value['user_id'])->value('nick');
				$data['data'][$key]['cashier_name'] = Db::name('system_user')->where('id',$value['cashier_id'])->value('nick');
				$data['data'][$key]['adviser_name'] = Db::name('system_user')->where('id',$value['adviser_id'])->value('nick');
				$data['data'][$key]['finance_name'] = Db::name('system_user')->where('id',$value['finance_id'])->value('nick');
				$data['data'][$key]['technician_name'] = Db::name('system_user')->where('id','in',$value['technician_ids'])->column('nick');
				$data['data'][$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);

			}
			$data['count'] = Db::name('aftermarket_liao')->where('shop_id',session('shop_id'))->count('id');
			$data['code'] = 0;
			return json($data);
		} 
		return $this->fetch();
	}
	public function lookRefund()
	{
		$id = $this->request->param('id');
		$lists = Db::name("aftermarket_liao")->where('id',$id)->value('multiple');
		$this->assign('lists',json_decode($lists,true));
		// halt($lists);
		return $this->fetch();
	}
	/**
	 * [addRefund 新增退款]
	 */
	public function addRefund()
	{
		if($this->request->isPost()){
			$postData = $this->request->post();
			if($postData['price'] <0){
				return $this->axiosMsg('退款金额不能为负数', false);
			}
			Db::startTrans();
			try {
				$postData['sn'] = create_order_sn();
				// 退卡单
            	$postData['createtime'] = time();
            	$postData['shop_id'] = session('shop_id');
            	$multipleSelection = $postData['multipleSelection'];

            	$postData['technician_ids'] = implode(',',$postData['technician_ids']);
            	$postData['multiple'] = json_encode($postData['multipleSelection']);
            	unset($postData['multipleSelection']);
            	Db::name('aftermarket_liao')->insert($postData);

            	if($postData['account_id'] == 0){
            		$balanceData = [
	                	'user_id' => $postData['user_id'],
	                	'type' => 1,
	                	'price' => $postData['price'],
	                	'sn' => $postData['sn'],
	                	'createtime' => time(),
	                	'is_give' => 1,
	                	'updatetime' => time()
	                ];
	                Db::name('user_balance_log')->insert($balanceData);
            	}else{
            		$sys = [
	            		'sn' => $postData['sn'],
	            		'account_id' => $postData['account_id'],
	            		'type' => 10,
	            		'price' => $postData['price'],
	            		'is_effective' => 1,
	            		'cate' => 2,
	            		'user_id' => $postData['user_id'],
	            		'createtime' => time(),
	            		'updatetime' => time(),
	            	];
	            	Db::name('system_balance_log')->insert($sys);
            	}
            	


            	// 绩效********************************************************
                $meirongshi = Db::name('system_user')->where('id','in',$postData['technician_ids'])->column('id,nick');
                $jixiao = [];
                // dump($value );
                $jixiao[] = [
                    'admin_id' => $postData['adviser_id'],  
                    'user_id' => $postData['user_id'],
                    'project' => '会员退款',
                    'num' => 1,
                    'price' => $postData['price'],
                    'shougong' => 0,
                    'settlement' => '销售退回',
                    'shop_id' => $postData['shop_id'],
                    'admin_type' => '顾问',
                    'proportion' => 0,
                    'createtime' => date('Y-m-d H:i:s',time()),
                    'sn' => $postData['sn'],
                ];
                foreach ($meirongshi as $k => $v) {
                    $jixiao[] = [
                        'admin_id' => $k,  
                        'user_id' => $postData['user_id'],
                        'project' => '会员退款',
                        'num' => 1,
                        'price' => $postData['price'],
                        'shougong' => 0,
                        'settlement' => '销售退回',
                        'shop_id' => $postData['shop_id'],
                        'admin_type' => '美容师',
                        'proportion' => 0,
                        'createtime' => date('Y-m-d H:i:s',time()),
                        'sn' => $postData['sn'],
                    ];
                }
                if(count($jixiao) > 0){
                    Db::name('achievements')->insertAll($jixiao);
                }
                // 绩效********************************************************
                // 扣除疗程卡
                foreach ($multipleSelection as $key => $value) {
                	 Db::name('user_card_log')->where('id',$value['id'])->update(['use'=>3,'updatetime'=>time()]);
                }
               
				Db::commit();
			} catch (Exception $e) {
				Db::rollback();
				return $this->axiosMsg($e->getMessage(),false);
			}
			return $this->axiosMsg('退款成功',true);
		}
		$account_arr = AccountModel::where('status',1)->all();
        $this->assign('accountArr', $account_arr);
		return $this->fetch();
	}

	/**
	 * [getProject 获取用户购买过的疗程卡]
	 * @return [type] [description]
	 */
	public function getProject()
	{
		$id = $this->request->param('id');
		$cards = Db::name('user_card')->alias('u')->join('course c','u.course_id=c.id')->field('u.*,c.name')->where('u.user_id',$id)->select();
		$cardsArr = [];
		$ci = Db::name('user_card_log')->where('user_id',$id)->where('use',1)->select();
		foreach ($cards as $key => $value) {
			foreach ($ci as $k => $v) {
				if($value['sn'] == $v['sn']){
					$v['cardname'] = $value['name'];
					$v['cardprice'] = $value['price1'];
					if($v['type'] == 1){   //  项目
						$v['name'] = Db::name('project')->where('id',$v['pid'])->value('name');
					}else{
						$v['name'] = Db::name('product')->where('id',$v['pid'])->value('name');
					}
					$cardsArr[] = $v;
				}
			}
		}
		
		return json($cardsArr);
	}
	/**
	 * [card 退卡]
	 * @return [type] [description]
	 */
	public function card()
	{
		if($this->request->isAjax()){
			$page = $this->request->param('page');
			$limit = $this->request->param('limit');
			// $page = $this->request->param('page');
			$data['data'] = Db::name('aftermarket_card')->where('shop_id',session('shop_id'))->order('id desc')->select();
			foreach ($data['data'] as $key => $value) {
				$data['data'][$key]['user_name'] = Db::name('user')->where('id',$value['user_id'])->value('nick');
				$data['data'][$key]['cashier_name'] = Db::name('system_user')->where('id',$value['cashier_id'])->value('nick');
				$data['data'][$key]['adviser_name'] = Db::name('system_user')->where('id',$value['adviser_id'])->value('nick');
				$data['data'][$key]['finance_name'] = Db::name('system_user')->where('id',$value['finance_id'])->value('nick');
				$data['data'][$key]['technician_name'] = Db::name('system_user')->where('id','in',$value['technician_ids'])->column('nick');
				$data['data'][$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);

			}
			$data['count'] = Db::name('aftermarket_card')->where('shop_id',session('shop_id'))->count('id');
			$data['code'] = 0;
			return json($data);
		}
		return $this->fetch();
	}
	/**
	 * [addCard 新增退卡]
	 */
	public function addCard()
	{	
		if($this->request->isPost()){
			$postData = $this->request->post();

			$userModel = new UserModel;
            $userBalance = $userModel->getUserBalance($postData['user_id'],1);
            if($userBalance < $postData['price']){
            	return $this->error('退卡金额过多！');
            }
            if($postData['price'] <= 0){
            	return $this->error('退卡金额必须大于0！');
            }
            Db::startTrans();

            try {
            	// 退卡单
            	$postData['createtime'] = time();
            	Db::name('aftermarket_card')->insert($postData);

            	// 银行卡支出
            	$sys = [
            		'sn' => $postData['sn'],
            		'account_id' => $postData['account_id'],
            		'type' => 9,
            		'price' => $postData['price'],
            		'is_effective' => 1,
            		'cate' => 2,
            		'user_id' => $postData['user_id'],
            		'createtime' => time(),
            		'updatetime' => time(),
            	];
            	Db::name('system_balance_log')->insert($sys);


            	// 绩效********************************************************
                $meirongshi = Db::name('system_user')->where('id','in',$postData['technician_ids'])->column('id,nick');
                $jixiao = [];
                // dump($value );
                $jixiao[] = [
                    'admin_id' => $postData['adviser_id'],  
                    'user_id' => $postData['user_id'],
                    'project' => '会员退卡',
                    'num' => 1,
                    'price' => $postData['price'],
                    'shougong' => 0,
                    'settlement' => '销售退回',
                    'shop_id' => $postData['shop_id'],
                    'admin_type' => '顾问',
                    'proportion' => 0,
                    'createtime' => date('Y-m-d H:i:s',time()),
                    'sn' => $postData['sn'],
                ];
                foreach ($meirongshi as $k => $v) {
                    $jixiao[] = [
                        'admin_id' => $k,  
                        'user_id' => $postData['user_id'],
                        'project' => '会员退卡',
                        'num' => 1,
                        'price' => $postData['price'],
                        'shougong' => 0,
                        'settlement' => '销售退回',
                        'shop_id' => $postData['shop_id'],
                        'admin_type' => '美容师',
                        'proportion' => 0,
                        'createtime' => date('Y-m-d H:i:s',time()),
                        'sn' => $postData['sn'],
                    ];
                }
                if(count($jixiao) > 0){
                    Db::name('achievements')->insertAll($jixiao);
                }
                // 绩效********************************************************
                // 扣除会员卡
                $balanceData = [
                	'user_id' => $postData['user_id'],
                	'type' => 5,
                	'price' => $postData['price'],
                	'sn' => $postData['sn'],
                	'createtime' => time(),
                	'is_give' => 1,
                	'updatetime' => time()
                ];
                Db::name('user_balance_log')->insert($balanceData);
                
            	Db::commit();
            } catch (Exception $e) {
            	Db::rollback();
            	return $this->error($e->getMessage());
            }
            return $this->success('退卡成功！');
		}
		return $this->fetch();
	}
	/**
	 * [checkCard 审核退卡]
	 * @return [type] [description]
	 */
	public function checkCard()
	{
		$id = $this->request->param('id');
		$formData = Db::name('aftermarket_card')->where('id',$id)->find();
		if(!$formData){
			return $this->error('订单不存在');
		}
		$this->assign('formData',$formData);
		return $this->fetch('add_card');
	}


	public function product()
	{
		if($this->request->isAjax()){
			$page = $this->request->param('page');
			$limit = $this->request->param('limit');
			$where = [];
			$data['data'] = Db::name('aftermarket_product')->where($where)->page($page)->limit($limit)->order('id desc')->select();
			$data['count'] = Db::name('aftermarket_product')->where($where)->page($page)->limit($limit)->order('id desc')->count('id');
			foreach ($data['data'] as $key => $value) {
				$data['data'][$key]['user_name'] = Db::name('user')->where('id',$value['user_id'])->value('nick');
				$data['data'][$key]['cashier_name'] = Db::name('system_user')->where('id',$value['cashier_id'])->value('nick');
				$data['data'][$key]['adviser_name'] = Db::name('system_user')->where('id',$value['adviser_id'])->value('nick');
				$data['data'][$key]['finance_name'] = Db::name('system_user')->where('id',$value['finance_id'])->value('nick');
				$data['data'][$key]['technician_name'] = Db::name('system_user')->where('id','in',$value['technician_ids'])->column('nick');
				$data['data'][$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);

			}
			$data['code'] = 0;
			return json($data);
		}
		return $this->fetch();
	}
	/**
	 * [addProduct 添加推产品单]
	 */
	public function addProduct()
	{
		if($this->request->isPost()){
			$postData = $this->request->post();
			Db::startTrans();
			$sn = create_order_sn();
			// halt($postData);
            try {
            	// 退产品单
            	$postData['createtime'] = time();
            	$productArr = $postData['productData'];
            	if(empty($postData['productData']) || !isset($postData['productData'])){
					throw new \Exception("产品不能为空", 1);
            	}
            	
            	// 退单表
            	$postData['products'] = json_encode($productArr);
            	$postData['sn'] = $sn;
            	$postData['technician_ids'] = implode(',',$postData['technician_ids']);
            	$postData['shop_id'] = session('shop_id');
            	unset($postData['productData']);
            	// halt($postData);
            	Db::name('aftermarket_product')->insert($postData);
            	// 判断是退现金还是退到会员卡
            	if($postData['account_id'] == 0){
            		$balanceData = [
	                	'user_id' => $postData['user_id'],
	                	'type' => 1,
	                	'price' => $postData['price'],
	                	'sn' => $sn,
	                	'createtime' => time(),
	                	'is_give' => 1,
	                	'updatetime' => time()
	                ];
	                Db::name('user_balance_log')->insert($balanceData);
            	}else{
            		$sys = [
	            		'sn' => $sn,
	            		'account_id' => $postData['account_id'],
	            		'type' => 11,
	            		'price' => $postData['price'],
	            		'is_effective' => 1,
	            		'cate' => 2,
	            		'user_id' => $postData['user_id'],
	            		'createtime' => time(),
	            		'updatetime' => time(),
	            	];
	            	Db::name('system_balance_log')->insert($sys);
            	}
            	

            	// 绩效********************************************************
                $meirongshi = Db::name('system_user')->where('id','in',$postData['technician_ids'])->column('id,nick');
                $jixiao = [];
                // dump($value );
                $jixiao[] = [
                    'admin_id' => $postData['adviser_id'],  
                    'user_id' => $postData['user_id'],
                    'project' => '会员退产品',
                    'num' => 1,
                    'price' => $postData['price'],
                    'shougong' => 0,
                    'settlement' => '销售退回',
                    'shop_id' => $postData['shop_id'],
                    'admin_type' => '顾问',
                    'proportion' => 0,
                    'createtime' => date('Y-m-d H:i:s',time()),
                    'sn' => $postData['sn'],
                ];
                foreach ($meirongshi as $k => $v) {
                    $jixiao[] = [
                        'admin_id' => $k,  
                        'user_id' => $postData['user_id'],
                        'project' => '会员退产品',
                        'num' => 1,
                        'price' => $postData['price'],
                        'shougong' => 0,
                        'settlement' => '销售退回',
                        'shop_id' => $postData['shop_id'],
                        'admin_type' => '美容师',
                        'proportion' => 0,
                        'createtime' => date('Y-m-d H:i:s',time()),
                        'sn' => $postData['sn'],
                    ];
                }
                if(count($jixiao) > 0){
                    Db::name('achievements')->insertAll($jixiao);
                }
                // 绩效********************************************************
                $stock = [];
                $warehouse_id = Db::name('warehouse')->where('shop_id',$postData['shop_id'])->where('type',0)->value('id');
               	foreach ($productArr as $key => $value) {
               		$stock[] = [
						'product_id' => $value['id'],
						'product_num' => $value['num'],
						'product_name' => $value['name'],
						'shop_id' => $postData['shop_id'],
						'sn' => $postData['sn'],
						'type' => '入库',
						'detailed_type' => 8,
						'user_id' => $postData['user_id'],
						'warehouse_id' => $warehouse_id,
						'createtime' => time(),
						'status' => 1,
						'bak' => '销售退回',
						'updatetime' => time(),
						'unit_price' => 0,
						'price' => $value['price2'],
               		];
               	}
                Db::name('stock')->insertAll($stock);
            	Db::commit();
            } catch (Exception $e) {
            	Db::rollback();
            	return $this->axiosMsg($e->getMessage(),false);
            	// return $this->error($e->getMessage());
            }
            return $this->axiosMsg('退卡成功！', true);
            // return $this->success('退卡成功！');

		}
		$account_arr = AccountModel::where('status',1)->all();
        $this->assign('accountArr', $account_arr);
		$products = Db::name('product')->where('status',1)->field('id,name,price2')->all();
		$this->assign('products', $products);
		return $this->fetch();
	}


	public function lookProduct()
	{
		$id = $this->request->param('id');
		$productArr = Db::name('aftermarket_product')->where('id',$id)->value('products');
		if(!$productArr){
			return $this->error('订单不存在或没有权限');
		}
		$this->assign('productArr', json_decode($productArr,true));
		return $this->fetch();
	}
}
